package swing_UI;

import java.util.ArrayList;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class Client implements Runnable{
	public static enum Status{
		CONNECTED,
		DISCONNECTED,
		ERROR
	}
	private Thread t;
	private Status status;
	private Integer id;
	private ArrayList<ChangeListener> changelisteners;
	
	
	public Client(Integer id)
	{
		this.status = Status.DISCONNECTED;
		this.id = id;
		this.changelisteners = new ArrayList<ChangeListener>();
		
	}
	
	public void init()
	{
		t = new Thread(this);
		t.start();
	}
	public Status getStatus()
	{
		return this.status;
	}
	public void setStatus(Status status)
	{
		if(status != this.status)
		{
			
			this.status = status;
			fireChangeEvent();
		}
	}
	public Integer getID()
	{
		return this.id;
	}
	//Change listener stuff
	public void addChangeListener(ChangeListener c)
	{
		
		this.changelisteners.add(c);
	}
	public void removeChangeListener(ChangeListener c)
	{
		if(this.changelisteners.contains(c)){
			this.changelisteners.remove(c);
		}
		
	}
	public ChangeListener[] getChangeListeners()
	{
		
		return this.changelisteners.toArray(new ChangeListener[5]);
	}
	
	public void fireChangeEvent()
	{
		for(ChangeListener c: this.changelisteners)
		{
			c.stateChanged(new ChangeEvent(this));
		}
	}
	public void run()
	{
		//Elaborate simulation of connection/disconnection behavior
		while(true)
		{
			try {
				t.sleep((int)Math.floor(Math.random()*10000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int rand = (int)Math.floor(Math.random()*100);
			if(this.status == Status.CONNECTED)
			{
				if(rand <= 0.1)
				{
					this.setStatus(Status.ERROR);
				}
				else if(rand <= 20)
				{
					this.setStatus(Status.DISCONNECTED);
				}
			}
			else if(this.status == Status.DISCONNECTED)
			{
				if(rand <= 30)
				{
					this.setStatus(Status.CONNECTED);
				}
			}	
				
		}
		
	}
	
}
